home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / Languages / Python 1.1 / Python / pythonrun.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-09-29  |  13.0 KB  |  693 lines  |  [TEXT/KAHL]

  1. /***********************************************************
  2. Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
  3. Amsterdam, The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its 
  8. documentation for any purpose and without fee is hereby granted, 
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in 
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI not be used in advertising or publicity pertaining to
  13. distribution of the software without specific, written prior permission.
  14.  
  15. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
  16. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  17. FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
  18. FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  19. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  20. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  21. OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  22.  
  23. ******************************************************************/
  24.  
  25. /* Python interpreter top-level routines, including init/exit */
  26.  
  27. #include "allobjects.h"
  28.  
  29. #include "grammar.h"
  30. #include "node.h"
  31. #include "parsetok.h"
  32. #include "graminit.h"
  33. #include "errcode.h"
  34. #include "sysmodule.h"
  35. #include "compile.h"
  36. #include "eval.h"
  37. #include "ceval.h"
  38. #include "pythonrun.h"
  39. #include "import.h"
  40. #include "marshal.h"
  41.  
  42. #ifdef HAVE_SIGNAL_H
  43. #include <signal.h>
  44. #endif
  45.  
  46. extern char *getpythonpath();
  47.  
  48. extern grammar gram; /* From graminit.c */
  49.  
  50. /* Forward */
  51. static object *run_err_node PROTO((node *n, char *filename,
  52.                    object *globals, object *locals));
  53. static object *run_node PROTO((node *n, char *filename,
  54.                    object *globals, object *locals));
  55. static void err_input PROTO((perrdetail *));
  56. static void initsigs PROTO((void));
  57.  
  58. int debugging; /* Needed by parser.c */
  59. int verbose; /* Needed by import.c */
  60. int suppress_print; /* Needed by ceval.c */
  61.  
  62. /* Initialize all */
  63.  
  64. void
  65. initall()
  66. {
  67.     static int inited;
  68.     
  69.     if (inited)
  70.         return;
  71.     inited = 1;
  72.     
  73.     initimport();
  74.     
  75.     /* Modules '__builtin__' and 'sys' are initialized here,
  76.        they are needed by random bits of the interpreter.
  77.        All other modules are optional and are initialized
  78.        when they are first imported. */
  79.     
  80.     initbuiltin(); /* Also initializes builtin exceptions */
  81.     initsys();
  82.  
  83.     setpythonpath(getpythonpath());
  84.  
  85.     initsigs(); /* Signal handling stuff, including initintr() */
  86. }
  87.  
  88. /* Parse input from a file and execute it */
  89.  
  90. int
  91. run(fp, filename)
  92.     FILE *fp;
  93.     char *filename;
  94. {
  95.     if (filename == NULL)
  96.         filename = "???";
  97.     if (isatty((int)fileno(fp)))
  98.         return run_tty_loop(fp, filename);
  99.     else
  100.         return run_script(fp, filename);
  101. }
  102.  
  103. int
  104. run_tty_loop(fp, filename)
  105.     FILE *fp;
  106.     char *filename;
  107. {
  108.     object *v;
  109.     int ret;
  110.     v = sysget("ps1");
  111.     if (v == NULL) {
  112.         sysset("ps1", v = newstringobject(">>> "));
  113.         XDECREF(v);
  114.     }
  115.     v = sysget("ps2");
  116.     if (v == NULL) {
  117.         sysset("ps2", v = newstringobject("... "));
  118.         XDECREF(v);
  119.     }
  120.     for (;;) {
  121.         ret = run_tty_1(fp, filename);
  122. #ifdef REF_DEBUG
  123.         fprintf(stderr, "[%ld refs]\n", ref_total);
  124. #endif
  125.         if (ret == E_EOF)
  126.             return 0;
  127.         /*
  128.         if (ret == E_NOMEM)
  129.             return -1;
  130.         */
  131.     }
  132. }
  133.  
  134. int
  135. run_tty_1(fp, filename)
  136.     FILE *fp;
  137.     char *filename;
  138. {
  139.     object *m, *d, *v, *w;
  140.     node *n;
  141.     perrdetail err;
  142.     char *ps1, *ps2;
  143.     v = sysget("ps1");
  144.     w = sysget("ps2");
  145.     if (v != NULL && is_stringobject(v)) {
  146.         INCREF(v);
  147.         ps1 = getstringvalue(v);
  148.     }
  149.     else {
  150.         v = NULL;
  151.         ps1 = "";
  152.     }
  153.     if (w != NULL && is_stringobject(w)) {
  154.         INCREF(w);
  155.         ps2 = getstringvalue(w);
  156.     }
  157.     else {
  158.         w = NULL;
  159.         ps2 = "";
  160.     }
  161.     BGN_SAVE
  162.     n = parsefile(fp, filename, &gram, single_input, ps1, ps2, &err);
  163.     END_SAVE
  164.     XDECREF(v);
  165.     XDECREF(w);
  166.     if (n == NULL) {
  167.         if (err.error == E_EOF) {
  168.             if (err.text)
  169.                 free(err.text);
  170.             return E_EOF;
  171.         }
  172.         err_input(&err);
  173.         print_error();
  174.         return err.error;
  175.     }
  176.     m = add_module("__main__");
  177.     if (m == NULL)
  178.         return -1;
  179.     d = getmoduledict(m);
  180.     v = run_node(n, filename, d, d);
  181.     flushline();
  182.     if (v == NULL) {
  183.         print_error();
  184.         return -1;
  185.     }
  186.     DECREF(v);
  187.     return 0;
  188. }
  189.  
  190. int
  191. run_script(fp, filename)
  192.     FILE *fp;
  193.     char *filename;
  194. {
  195.     object *m, *d, *v;
  196.     char *ext;
  197.  
  198.     m = add_module("__main__");
  199.     if (m == NULL)
  200.         return -1;
  201.     d = getmoduledict(m);
  202.     ext = filename + strlen(filename) - 4;
  203.     if ( strcmp(ext, ".pyc") == 0 ) {
  204.         /* Try to run a pyc file. First, re-open in binary */
  205.         fclose(fp);
  206.         if( (fp = fopen(filename, "rb")) == NULL ) {
  207.             fprintf(stderr, "python: Can't reopen .pyc file\n");
  208.             return -1;
  209.         }
  210.         v = run_pyc_file(fp, filename, d, d);
  211.     } else {
  212.         v = run_file(fp, filename, file_input, d, d);
  213.     }
  214.     flushline();
  215.     if (v == NULL) {
  216.         print_error();
  217.         return -1;
  218.     }
  219.     DECREF(v);
  220.     return 0;
  221. }
  222.  
  223. int
  224. run_command(command)
  225.     char *command;
  226. {
  227.     object *m, *d, *v;
  228.     m = add_module("__main__");
  229.     if (m == NULL)
  230.         return -1;
  231.     d = getmoduledict(m);
  232.     v = run_string(command, file_input, d, d);
  233.     flushline();
  234.     if (v == NULL) {
  235.         print_error();
  236.         return -1;
  237.     }
  238.     DECREF(v);
  239.     return 0;
  240. }
  241.  
  242. void
  243. print_error()
  244. {
  245.     object *exception, *v, *f;
  246.     err_get(&exception, &v);
  247.     if (exception == NULL) {
  248.         fprintf(stderr, "print_error called but no exception\n");
  249.         abort();
  250.     }
  251.     if (exception == SystemExit) {
  252.         if (v == NULL || v == None)
  253.             goaway(0);
  254.         if (is_intobject(v))
  255.             goaway((int)getintvalue(v));
  256.         else {
  257.             /* OK to use real stderr here */
  258.             printobject(v, stderr, PRINT_RAW);
  259.             fprintf(stderr, "\n");
  260.             goaway(1);
  261.         }
  262.     }
  263.     sysset("last_type", exception);
  264.     sysset("last_value", v);
  265.     f = sysget("stderr");
  266.     if (f == NULL)
  267.         fprintf(stderr, "lost sys.stderr\n");
  268.     else {
  269.         printtraceback(f);
  270.         if (exception == SyntaxError) {
  271.             object *message;
  272.             char *filename, *text;
  273.             int lineno, offset;
  274.             if (!getargs(v, "(O(ziiz))", &message,
  275.                      &filename, &lineno, &offset, &text))
  276.                 err_clear();
  277.             else {
  278.                 char buf[10];
  279.                 writestring("  File \"", f);
  280.                 if (filename == NULL)
  281.                     writestring("<string>", f);
  282.                 else
  283.                     writestring(filename, f);
  284.                 writestring("\", line ", f);
  285.                 sprintf(buf, "%d", lineno);
  286.                 writestring(buf, f);
  287.                 writestring("\n", f);
  288.                 if (text != NULL) {
  289.                     char *nl;
  290.                     if (offset > 0 &&
  291.                         offset == strlen(text))
  292.                         offset--;
  293.                     for (;;) {
  294.                         nl = strchr(text, '\n');
  295.                         if (nl == NULL ||
  296.                             nl-text >= offset)
  297.                             break;
  298.                         offset -= (nl+1-text);
  299.                         text = nl+1;
  300.                     }
  301.                     while (*text == ' ' || *text == '\t') {
  302.                         text++;
  303.                         offset--;
  304.                     }
  305.                     writestring("    ", f);
  306.                     writestring(text, f);
  307.                     if (*text == '\0' ||
  308.                         text[strlen(text)-1] != '\n')
  309.                         writestring("\n", f);
  310.                     writestring("    ", f);
  311.                     offset--;
  312.                     while (offset > 0) {
  313.                         writestring(" ", f);
  314.                         offset--;
  315.                     }
  316.                     writestring("^\n", f);
  317.                 }
  318.                 INCREF(message);
  319.                 DECREF(v);
  320.                 v = message;
  321.             }
  322.         }
  323.         if (writeobject(exception, f, PRINT_RAW) != 0)
  324.             err_clear();
  325.         if (v != NULL && v != None) {
  326.             writestring(": ", f);
  327.             if (writeobject(v, f, PRINT_RAW) != 0)
  328.                 err_clear();
  329.         }
  330.         writestring("\n", f);
  331.     }
  332.     XDECREF(exception);
  333.     XDECREF(v);
  334. }
  335.  
  336. object *
  337. run_string(str, start, globals, locals)
  338.     char *str;
  339.     int start;
  340.     object *globals, *locals;
  341. {
  342.     return run_err_node(parse_string(str, start),
  343.                 "<string>", globals, locals);
  344. }
  345.  
  346. object *
  347. run_file(fp, filename, start, globals, locals)
  348.     FILE *fp;
  349.     char *filename;
  350.     int start;
  351.     object *globals, *locals;
  352. {
  353.     return run_err_node(parse_file(fp, filename, start),
  354.                 filename, globals, locals);
  355. }
  356.  
  357. static object *
  358. run_err_node(n, filename, globals, locals)
  359.     node *n;
  360.     char *filename;
  361.     object *globals, *locals;
  362. {
  363.     if (n == NULL)
  364.         return  NULL;
  365.     return run_node(n, filename, globals, locals);
  366. }
  367.  
  368. static object *
  369. run_node(n, filename, globals, locals)
  370.     node *n;
  371.     char *filename;
  372.     object *globals, *locals;
  373. {
  374.     codeobject *co;
  375.     object *v;
  376.     co = compile(n, filename);
  377.     freetree(n);
  378.     if (co == NULL)
  379.         return NULL;
  380.     v = eval_code(co, globals, locals, (object *)NULL, (object *)NULL);
  381.     DECREF(co);
  382.     return v;
  383. }
  384.  
  385. object *
  386. run_pyc_file(fp, filename, globals, locals)
  387.     FILE *fp;
  388.     char *filename;
  389.     object *globals, *locals;
  390. {
  391.     codeobject *co;
  392.     object *v;
  393.     long magic;
  394.     long get_pyc_magic();
  395.  
  396.     magic = rd_long(fp);
  397.     if (magic != get_pyc_magic()) {
  398.         err_setstr(RuntimeError,
  399.                "Bad magic number in .pyc file");
  400.         return NULL;
  401.     }
  402.     (void) rd_long(fp);
  403.     v = rd_object(fp);
  404.     fclose(fp);
  405.     if (v == NULL || !is_codeobject(v)) {
  406.         XDECREF(v);
  407.         err_setstr(RuntimeError,
  408.                "Bad code object in .pyc file");
  409.         return NULL;
  410.     }
  411.     co = (codeobject *)v;
  412.     v = eval_code(co, globals, locals, (object *)NULL, (object *)NULL);
  413.     DECREF(co);
  414.     return v;
  415. }
  416.  
  417. object *
  418. compile_string(str, filename, start)
  419.     char *str;
  420.     char *filename;
  421.     int start;
  422. {
  423.     node *n;
  424.     int err;
  425.     codeobject *co;
  426.     n = parse_string(str, start);
  427.     if (n == NULL)
  428.         return NULL;
  429.     co = compile(n, filename);
  430.     freetree(n);
  431.     return (object *)co;
  432. }
  433.  
  434. /* Simplified interface to parsefile -- return node or set exception */
  435.  
  436. node *
  437. parse_file(fp, filename, start)
  438.     FILE *fp;
  439.     char *filename;
  440.     int start;
  441. {
  442.     node *n;
  443.     perrdetail err;
  444.     BGN_SAVE
  445.     n = parsefile(fp, filename, &gram, start,
  446.                 (char *)0, (char *)0, &err);
  447.     END_SAVE
  448.     if (n == NULL)
  449.         err_input(&err);
  450.     return n;
  451. }
  452.  
  453. /* Simplified interface to parsestring -- return node or set exception */
  454.  
  455. node *
  456. parse_string(str, start)
  457.     char *str;
  458.     int start;
  459. {
  460.     node *n;
  461.     perrdetail err;
  462.     n = parsestring(str, &gram, start, &err);
  463.     if (n == NULL)
  464.         err_input(&err);
  465.     return n;
  466. }
  467.  
  468. /* Set the error appropriate to the given input error code (see errcode.h) */
  469.  
  470. static void
  471. err_input(err)
  472.     perrdetail *err;
  473. {
  474.     object *v, *w;
  475.     char *msg = NULL;
  476.     v = mkvalue("(ziiz)", err->filename,
  477.                 err->lineno, err->offset, err->text);
  478.     if (err->text != NULL) {
  479.         free(err->text);
  480.         err->text = NULL;
  481.     }
  482.     switch (err->error) {
  483.     case E_SYNTAX:
  484.         msg = "invalid syntax";
  485.         break;
  486.     case E_TOKEN:
  487.         msg = "invalid token";
  488.  
  489.         break;
  490.     case E_INTR:
  491.         err_set(KeyboardInterrupt);
  492.         return;
  493.     case E_NOMEM:
  494.         err_nomem();
  495.         return;
  496.     case E_EOF:
  497.         msg = "unexpected EOF while parsing";
  498.         break;
  499.     default:
  500.         fprintf(stderr, "error=%d\n", err->error);
  501.         msg = "unknown parsing error";
  502.         break;
  503.     }
  504.     w = mkvalue("(sO)", msg, v);
  505.     XDECREF(v);
  506.     err_setval(SyntaxError, w);
  507.     XDECREF(w);
  508. }
  509.  
  510. /* Print fatal error message and abort */
  511.  
  512. void
  513. fatal(msg)
  514.     char *msg;
  515. {
  516.     fprintf(stderr, "Fatal Python error: %s\n", msg);
  517.     abort();
  518. }
  519.  
  520. /* Clean up and exit */
  521.  
  522. #ifdef WITH_THREAD
  523. #include "thread.h"
  524. int threads_started = 0; /* Set by threadmodule.c and maybe others */
  525. #endif
  526.  
  527. #define NEXITFUNCS 32
  528. static void (*exitfuncs[NEXITFUNCS])();
  529. static int nexitfuncs = 0;
  530.  
  531. int Py_AtExit(func)
  532.     void (*func) PROTO((void));
  533. {
  534.     if (nexitfuncs >= NEXITFUNCS)
  535.         return -1;
  536.     exitfuncs[nexitfuncs++] = func;
  537.     return 0;
  538. }
  539.  
  540. void
  541. cleanup()
  542. {
  543.     object *exitfunc = sysget("exitfunc");
  544.  
  545.     if (exitfunc) {
  546.         object *arg;
  547.         object *res;
  548.         sysset("exitfunc", (object *)NULL);
  549.         arg = newtupleobject(0);
  550.         if (arg == NULL)
  551.             res = NULL;
  552.         else {
  553.             res = call_object(exitfunc, arg);
  554.             DECREF(arg);
  555.         }
  556.         if (res == NULL) {
  557.             fprintf(stderr, "Error in sys.exitfunc:\n");
  558.             print_error();
  559.         }
  560.     }
  561.  
  562.     flushline();
  563.  
  564.     while (nexitfuncs > 0)
  565.         (*exitfuncs[--nexitfuncs])();
  566. }
  567.  
  568. #ifdef COUNT_ALLOCS
  569. extern void dump_counts PROTO((void));
  570. #endif
  571.  
  572. void
  573. goaway(sts)
  574.     int sts;
  575. {
  576.     cleanup();
  577.  
  578. #ifdef COUNT_ALLOCS
  579.     dump_counts();
  580. #endif
  581.  
  582. #ifdef WITH_THREAD
  583.  
  584.     /* Other threads may still be active, so skip most of the
  585.        cleanup actions usually done (these are mostly for
  586.        debugging anyway). */
  587.     
  588.     (void) save_thread();
  589. #ifndef NO_EXIT_PROG
  590.     if (threads_started)
  591.         _exit_prog(sts);
  592.     else
  593.         exit_prog(sts);
  594. #else /* !NO_EXIT_PROG */
  595.     if (threads_started)
  596.         _exit(sts);
  597.     else
  598.         exit(sts);
  599. #endif /* !NO_EXIT_PROG */
  600.     
  601. #else /* WITH_THREAD */
  602.     
  603.     doneimport();
  604.     
  605.     err_clear();
  606.  
  607. #ifdef REF_DEBUG
  608.     fprintf(stderr, "[%ld refs]\n", ref_total);
  609. #endif
  610.  
  611. #ifdef TRACE_REFS
  612.     if (askyesno("Print left references?")) {
  613.         printrefs(stderr);
  614.     }
  615. #endif /* TRACE_REFS */
  616.  
  617.     exit(sts);
  618. #endif /* WITH_THREAD */
  619.     /*NOTREACHED*/
  620. }
  621.  
  622. #ifdef HAVE_SIGNAL_H
  623. static RETSIGTYPE
  624. sighandler(sig)
  625.     int sig;
  626. {
  627.     signal(sig, SIG_DFL); /* Don't catch recursive signals */
  628.     cleanup(); /* Do essential clean-up */
  629. #ifdef HAVE_GETPID
  630.     kill(getpid(), sig); /* Pretend the signal killed us */
  631. #else
  632.     exit(1);
  633. #endif
  634.     /*NOTREACHED*/
  635. }
  636. #endif
  637.  
  638. static void
  639. initsigs()
  640. {
  641.     RETSIGTYPE (*t)();
  642. #ifdef HAVE_SIGNAL_H
  643. #ifdef SIGPIPE
  644.     signal(SIGPIPE, SIG_IGN);
  645. #endif
  646. #ifdef SIGHUP
  647.     t = signal(SIGHUP, SIG_IGN);
  648.     if (t == SIG_DFL)
  649.         signal(SIGHUP, sighandler);
  650.     else
  651.         signal(SIGHUP, t);
  652. #endif              
  653. #ifdef SIGTERM
  654.     t = signal(SIGTERM, SIG_IGN);
  655.     if (t == SIG_DFL)
  656.         signal(SIGTERM, sighandler);
  657.     else
  658.         signal(SIGTERM, t);
  659. #endif
  660. #endif /* HAVE_SIGNAL_H */
  661.     initintr(); /* May imply initsignal() */
  662. }
  663.  
  664. #ifdef TRACE_REFS
  665. /* Ask a yes/no question */
  666.  
  667. int
  668. askyesno(prompt)
  669.     char *prompt;
  670. {
  671.     char buf[256];
  672.     
  673.     printf("%s [ny] ", prompt);
  674.     if (fgets(buf, sizeof buf, stdin) == NULL)
  675.         return 0;
  676.     return buf[0] == 'y' || buf[0] == 'Y';
  677. }
  678. #endif
  679.  
  680. #ifdef MPW
  681.  
  682. /* Check for file descriptor connected to interactive device.
  683.    Pretend that stdin is always interactive, other files never. */
  684.  
  685. int
  686. isatty(fd)
  687.     int fd;
  688. {
  689.     return fd == fileno(stdin);
  690. }
  691.  
  692. #endif
  693.